<?php
namespace Todo\Model\Rate;

use Todo\Model\TreeModel;

class NormModel extends TreeModel
{
    protected $order = 'tpl_id DESC, pid ASC, sort ASC';

    public $tableName = 'rate_norm';

    public $_validate = array(
        array('title', 'require', '请输入指标名称'),
        array('tpl_id', 'require', '请选择所属模板'),
        array('score', 'require', '请输入指标分数'),
        array('way', 'require', '请选择打分方式')
    );
    
    protected $_auto = array(
        array('tnt_id', 'auto_tnt', self::MODEL_INSERT, 'function')
    );
    
    protected function _before_insert(&$data,$options){
        if(!$data['pid']) return true;

        $score = $this->where(array('tpl_id'=>$data['tpl_id'],'pid'=>$data['pid']))->sum('score');
        $max = $this->keyFind($data['pid'],'score');
        if($score + $data['score'] > $max) {
            $this->error = '下级指标分数之和不能大于上级指标';
            return false;
        }

        return parent::_before_insert($data, $options);
    }

    protected function _before_update(&$data,$options){
        if(!$data['pid']) return true;

        $score = $this->where(array('tpl_id'=>$data['tpl_id'],'pid'=>$data['pid'], 'id'=>array('neq', $data['id'])))->sum('score');
        $max = $this->keyFind($data['pid'],'score');
        if($score + $data['score'] > $max) {
            $this->error = '下级指标分数之和不能大于上级指标';
            return false;
        }

        return parent::_before_update($data, $options);
    }
}